<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    width="50%"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <template #footer>
      <a-button @click="closeModal">取消</a-button>
      <a-button type="primary" @click="handleSubmit(false)">保存</a-button>
      <a-button type="primary" @click="handleSubmit(true)"
        >保存并继续添加</a-button
      >
    </template>
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '@/components/Modal';
import { BasicForm, useForm } from '@/components/Form/index';
import { formSchema } from './data';
import { useMessage } from '@/hooks/web/useMessage';
import { edit, add } from '@/api/sys/dev/lcTableManage';
const emit = defineEmits(['success', 'register']);
let isUpdate = ref(true);
const { createMessage } = useMessage();
const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 100,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 12 },
});

const [registerModal, { closeModal }] = useModalInner(async (data) => {
  resetFields();
  isUpdate.value = !!data?.isUpdate;

  if (unref(isUpdate)) {
    setFieldsValue({
      ...data.record,
    });
  }
});
const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

async function handleSubmit(hasNext: boolean) {
  try {
    const values = await validate();
    if (unref(isUpdate)) {
      await edit(values);
      createMessage.success('修改成功');
    } else {
      await add(values);
      createMessage.success('保存成功');
    }
    if (hasNext) {
      resetFields();
    } else {
      closeModal();
    }
    emit('success');
  } finally {
  }
}
</script>
